<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="归属部门" prop="deptId">
        <treeselect
          v-model="queryParams.deptId"
          :options="deptOptions"
          :disable-branch-nodes="false"
          :show-count="true"
          placeholder="请选择归属部门"
          :defaultExpandLevel="2"
          class="search-treeselect"
          style="width: 200px; margin-top: 2px"
        />
      </el-form-item> -->
      <el-form-item label="设施名称" prop="facilityName">
        <el-input
          v-model="queryParams.facilityName"
          placeholder="请输入设施名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设施编号" prop="facilityNum">
        <el-input
          v-model="queryParams.facilityNum"
          placeholder="请输入设施编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设施类型" prop="facilityType">
        <el-select
          v-model="queryParams.facilityType"
          placeholder="请选择设施类型"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in dict.type.base_facility_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['base:facility:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:facility:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:facility:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['base:facility:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="facilityList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column type="index" label="序号" width="60" align="left" />
      <el-table-column
        label="所属部门单位"
        align="left"
        prop="deptName"
        minWidth="150px"
      />

      <el-table-column
        label="设施名称"
        align="left"
        prop="facilityName"
        minWidth="150px"
      />
      <el-table-column
        label="设施编号"
        align="left"
        prop="facilityNum"
        minWidth="150px"
      />
      <el-table-column
        label="设施类型"
        align="left"
        prop="facilityType"
        width="100px"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.base_facility_type"
            :value="scope.row.facilityType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="满溢传感器"
        align="left"
        prop="deviceId"
        width="180"
      >
        <template slot-scope="scope">
          <el-link
            type="primary"
            v-if="scope.row.deviceId"
            @click="routeToDevicePage(scope.row.imei)"
            >{{ scope.row.imei }}</el-link
          >
          <span v-else>未绑定</span>
        </template>
      </el-table-column>
      <el-table-column
        label="设施规格"
        align="left"
        prop="facilitySpecifications"
        width="100px"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.facilitySpecifications }} cm</span>
        </template>
      </el-table-column>
      <el-table-column
        label="传感器告警距离"
        align="left"
        prop="alarmDistance"
        width="120px"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.alarmDistance }} cm</span>
        </template>
      </el-table-column>
      <el-table-column
        label="安装日期"
        align="left"
        prop="installDate"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.installDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="维护单位"
        align="left"
        prop="maintainBy"
        minWidth="100px"
      />
      <el-table-column label="照片" align="left" prop="photoPath" width="100px">
        <template slot-scope="scope">
          <i
            v-if="scope.row.photoPath"
            class="el-icon-view"
            style="cursor: pointer; color: #1890ff"
            @click="handleViewPic(scope.row.photoPath)"
          ></i>
        </template>
      </el-table-column>
      <el-table-column
        label="地址"
        align="left"
        prop="address"
        minWidth="150px"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        align="left"
        class-name="small-padding fixed-width"
        width="160px"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.deviceId"
            size="mini"
            type="text"
            icon="el-icon-scissors"
            @click="handleUnbind(scope.row)"
            v-hasPermi="['base:facility:bind']"
            >解绑</el-button
          >
          <el-button
            v-if="!scope.row.deviceId"
            size="mini"
            type="text"
            icon="el-icon-paperclip"
            @click="handleBind(scope.row)"
            v-hasPermi="['base:facility:bind']"
            >绑定</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['base:facility:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:facility:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设施管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :disable-branch-nodes="false"
                :show-count="true"
                placeholder="请选择归属部门"
                :defaultExpandLevel="2"
              />
            </el-form-item>
            <el-form-item label="设施名称" prop="facilityName">
              <el-input
                v-model="form.facilityName"
                placeholder="请输入设施名称"
              />
            </el-form-item>
            <el-form-item label="设施编号" prop="facilityNum">
              <el-input
                v-model="form.facilityNum"
                placeholder="请输入设施编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="照片" prop="photoPath">
              <upload-img
                actionUrl="/common/upload"
                :imgUrl.sync="form.photoPath"
                width="200px"
                height="150px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider>详情</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设施类型" prop="facilityType">
              <el-select
                v-model="form.facilityType"
                placeholder="请选择设施类型"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.base_facility_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设施规格" prop="facilitySpecifications">
              <el-input
                v-model="form.facilitySpecifications"
                placeholder="请输入设施规格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装日期" prop="installDate">
              <el-date-picker
                clearable
                v-model="form.installDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择安装日期"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="维护单位" prop="maintainBy">
              <el-input
                v-model="form.maintainBy"
                placeholder="请输入维护单位"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          label="传感器告警的距离"
          prop="alarmDistance"
          label-width="150px"
        >
          <el-input
            v-model="form.alarmDistance"
            placeholder="请输入传感器告警的距离"
          >
            <i slot="suffix">cm </i>
          </el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="form.address"
            class="loc-choose"
            placeholder="请输入地址"
          >
            <i
              slot="suffix"
              class="el-icon-location-outline"
              @click="showMapMarkDialog = true"
            ></i>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择位置 -->
    <map-mark
      :visible.sync="showMapMarkDialog"
      :gis="form"
      mapId="facility-map"
      @getMark="getMark"
    />
    <!--照片-->
    <el-dialog
      :visible.sync="picDialogVisible"
      title="预览"
      width="600px"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
    <!-- 绑定 -->
    <bindDeviceDialog
      :visible.sync="bindDialogVisible"
      :deviceType="bindDeviceType"
      :facilityObj="facilityObj"
      @refreshList="getList"
    />
  </div>
</template>

<script>
import {
  listFacility,
  getFacility,
  delFacility,
  addFacility,
  updateFacility,
  unbindDevice,
} from "@/api/base/facility";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { treeselect } from "@/api/system/dept";

import uploadImg from "@/views/components/uploadImg";
import MapMark from "@/views/components/mapMark";

import bindDeviceDialog from "./components/bindDeviceDialog";

export default {
  name: "Facility",
  components: {
    Treeselect,
    uploadImg,
    MapMark,
    bindDeviceDialog,
  },
  dicts: ["base_facility_type"],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设施管理表格数据
      facilityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        deviceId: undefined,
        facilityName: undefined,
        facilityNum: undefined,
        facilityType: undefined,
      },
      //部门树
      deptOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        facilityId: [
          { required: true, message: "设施id不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "部门id不能为空", trigger: "blur" },
        ],
        deviceId: [
          { required: true, message: "设备id不能为空", trigger: "blur" },
        ],
        facilityName: [
          { required: true, message: "设施名称不能为空", trigger: "blur" },
        ],
        facilityNum: [
          { required: true, message: "设施编号不能为空", trigger: "blur" },
        ],
        facilityType: [
          { required: true, message: "设施类型不能为空", trigger: "change" },
        ],
        facilitySpecifications: [
          { required: true, message: "设施规格不能为空", trigger: "blur" },
        ],
        alarmDistance: [
          {
            required: true,
            message: "传感器告警的距离(cm)不能为空",
            trigger: "blur",
          },
        ],
        installDate: [
          { required: true, message: "安装日期不能为空", trigger: "blur" },
        ],
        // maintainBy: [
        //   { required: true, message: "维护单位不能为空", trigger: "blur" },
        // ],
        lat: [{ required: true, message: "纬度不能为空", trigger: "blur" }],
        // photoPath: [
        //   { required: true, message: "照片不能为空", trigger: "blur" },
        // ],
        lng: [{ required: true, message: "经度不能为空", trigger: "blur" }],
        address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
      },
      showMapMarkDialog: false,
      picDialogVisible: false,
      dialogImageUrl: "",
      //绑定dialog
      bindDialogVisible: false,
      //设备类型
      bindDeviceType: "",
      facilityObj: null,
    };
  },
  computed: {
    deptId() {
      return this.$store.getters.choosedDeptId;
    },
  },
  watch: {
    deptId: function () {
      this.queryParams.deptId = this.deptId;
      this.getList();
    },
  },
  created() {
    this.getTreeselect();

    this.getList();
  },
  methods: {
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询设施管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.deptId = this.deptId;
      listFacility(this.queryParams).then((response) => {
        this.facilityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        facilityId: undefined,
        deptId: this.deptId,
        deviceId: undefined,
        facilityName: undefined,
        facilityNum: undefined,
        facilityType: undefined,
        facilitySpecifications: undefined,
        alarmDistance: undefined,
        installDate: undefined,
        maintainBy: undefined,
        lat: undefined,
        photoPath: undefined,
        lng: undefined,
        address: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.facilityId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设施管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const facilityId = row.facilityId || this.ids;
      getFacility(facilityId).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改设施管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.facilityId != null) {
            updateFacility(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addFacility(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const facilityIds = row.facilityId || this.ids;
      this.$modal
        .confirm('是否确认删除"' + (row.orderName || "已勾选") + '"的数据项?')
        .then(() => {
          this.loading = true;
          return delFacility(facilityIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "base/facility/export",
        {
          ...this.queryParams,
        },
        `设施_${new Date().getTime()}.xlsx`
      );
    },
    handleBind(row) {
      this.facilityObj = row;
      this.bindDeviceType = "overflow_sensor";
      this.bindDialogVisible = true;
    },
    /** 解绑 */
    handleUnbind(row) {
      this.$confirm('是否确认解绑"' + row.carNum + '"上的满溢传感器?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return unbindDevice({
            deviceId: row.deviceId,
            facilityId: row.facilityId,
          });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("解绑成功");
        })
        .catch(function () {});
    },
    routeToDevicePage(imei) {
      this.$router.push({
        // path: "/device",
        name: "Device",
        params: {
          imei: imei,
        },
      });
    },
    // 获取标记
    getMark(val) {
      console.log(val);
      this.form.address = val.address;
      this.form.lng = val.lng;
      this.form.lat = val.lat;
    },
    /**查看照片**/
    handleViewPic(url) {
      this.dialogImageUrl = url;
      this.picDialogVisible = true;
    },
  },
};
</script>
